package com.tianming.vrd.controller;

import com.tianming.vrd.entity.User;
import com.tianming.vrd.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper userMapper;

    /**
     * 登录
     *
     * @param user
     * @param rem
     * @param response
     * @param session
     * @return
     */
    @RequestMapping("/login")
    public int login(User user, String rem, HttpServletResponse response, HttpSession session){
        User u = userMapper.selectByUsername(user.getUsername());
        if (u!=null) {
            if (user.getPassword().equals(u.getPassword())) {
                //判断是否记住用户
                if (rem != null){
                    //创建Cookie 把用户名和密码保存
                    Cookie c1 = new Cookie("username",u.getUsername());
                    Cookie c2 = new Cookie("password",u.getPassword());
                    //设置Cookie保存一个月
                    c1.setMaxAge(60*60*24*30);
                    c2.setMaxAge(60*60*24*30);
                    //下发给客户端浏览器
                    response.addCookie(c1);
                    response.addCookie(c2);
                }
                session.setAttribute("user",u);
                return 1; //登录成功
            }else {
                return 2; //密码错误
            }
        }
        return 0;
    }

    /**
     * 验证是否登录
     * @param session
     * @return
     */
    @RequestMapping("/currentUser")
    public User currentUser(HttpSession session){
        return (User) session.getAttribute("user");
    }

    /**
     * 退出登录
     * @param session
     */
    @RequestMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }
}
